package algorithm_demo.demo01;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * https://leetcode.cn/problems/binary-tree-level-order-traversal-ii/
 *
 * @author Api
 * @date 2023/2/5 11:59
 */
public class Code29_BinaryTreeLevelOrderTraversalII {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }


    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        //因为为逆序，返回的列表中的List<Integer>为逆序，而倒序插入LinkedList的性能优于ArrayList
        List<List<Integer>> ans = new LinkedList<List<Integer>>();
        if(root == null){
            return ans;
        }
        // 队列，先进先出，每层遍历出元素后，弹出，并且判断是否存在左节点和右节点
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            List<Integer> curAns = new LinkedList<Integer>();
            for(int i =0; i < size; i++){
                TreeNode curNode = queue.poll();
                curAns.add(curNode.val);
                if(curNode.left != null){
                    queue.add(curNode.left);
                }
                if(curNode.right != null){
                    queue.add(curNode.right);
                }
            }
            ans.add(0, curAns);
        }
        return ans;
    }
}
